package com.dondedesigns.eh.controller.interceptors;

import java.util.Map;

import com.dondedesigns.eh.controller.index.UserAware;
import com.dondedesigns.eh.persistence.ApprovedStatus;
import com.dondedesigns.eh.persistence.User;
import com.dondedesigns.eh.persistence.dao.PermissionDAO;
import com.dondedesigns.eh.persistence.dao.UserDAO;
import com.dondedesigns.eh.util.EHConstants;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

public class AuthenticationInterceptor implements Interceptor {

	private UserDAO userDAO;
	private PermissionDAO permissionDAO;
	private User user;

	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void init() {
		// TODO Auto-generated method stub
		
	}
	
	public void setUserDAO(UserDAO userDAO) {
		this.userDAO = userDAO;

	}

	public void setPermissionDAO(PermissionDAO permissionDAO) {
		this.permissionDAO = permissionDAO;
	}

	@Override
	@SuppressWarnings("unchecked")
	public String intercept(ActionInvocation actionInvocation) throws Exception {
		Map session = actionInvocation.getInvocationContext().getSession();
		user = (User) session.get(EHConstants.USER);
		if (user == null || !user.getApprovedStatus().equals(ApprovedStatus.APPROVED)) {
			return Action.LOGIN;
		} else {
			user = userDAO.find(user.getId());
			session.put(EHConstants.USER, user);
			Action action = (Action) actionInvocation.getAction();
			if (action instanceof UserAware) {
				
				UserAware userAwareAction = (UserAware) action;
				userAwareAction.setUser(user);
			}
			String actionName = actionInvocation.getAction().getClass().getSimpleName();
			if (isRestrictedPage (actionName)) {
				if (checkAuthorization (actionName)) {
					return "unauthorized";
				}
			}
			return actionInvocation.invoke();
		}
		
	}

	private boolean isRestrictedPage(String actionName) {
		return permissionDAO.isRestrictedPage(actionName);
		
	}

	private boolean checkAuthorization(String actionName) {
		return userDAO.checkAuthorization(user.getId(), actionName);
	}

}
